package com.yangli.leecode.mashib.interview;

import java.util.Stack;

/**
 * @Description leecode772 https://leetcode.cn/problems/basic-calculator-iii/
 * 公式正确，不用考虑边界 负数在首位或者括号里面
 * @Author liyang
 * @Date 2023/2/7 13:05
 */
public class Fourteen {
    public static void main(String[] args){
        System.out.println(Fourteen.basicCalculatorIII("2+3*(2-1)"));
    }


    public static int basicCalculatorIII(String s){
        if (s == null || s.length() == 0) {
            return 0;
        }
        if (s.length() == 1) {
            return Integer.parseInt(s);
        }
        return function(s, 0)[0];


    }

    public static int[] function(String s, int index){
        Stack<String> stack = new Stack<>();
        int cur = 0;
        while (index < s.length() && !(s.charAt(index) == ')')) {
            if (s.charAt(index) >= '0' && s.charAt(index) <= '9') {
                cur = cur * 10 + (s.charAt(index++) - '0');
            } else if (s.charAt(index) == '(') {//左括号
                int[] res = function(s, index + 1);
                cur = res[0];
                index = res[1] + 1;
            } else {//运算符
                addNum(stack, String.valueOf(cur));
                stack.push(String.valueOf(s.charAt(index++)));//这个为运算符，直接加进去，暂时不用处理
                cur = 0;
            }
        }
        addNum(stack, String.valueOf(cur));
        return new int[]{getNum(stack), index};
    }

    public static void addNum(Stack<String> stack, String num){
        if (stack.empty()) {
            stack.push(num);
            return;
        }
        String last = stack.peek();
        if (last.equals("*") || last.equals("/")) {
            stack.pop();
            String lastNum = stack.pop();
            stack.push(String.valueOf(last.equals("*") ? Math.multiplyExact(Integer.parseInt(num), Integer.parseInt(lastNum)) : Math.floorDiv(Integer.parseInt(num), Integer.parseInt(lastNum))));
            return;
        }
        stack.push(num);

    }

    public static int getNum(Stack<String> stack){
        if (stack.empty()) {
            return 0;
        }
        int pre = 0;
        while (!stack.empty()) {
            String s = stack.pop();
            boolean add = true;
            if (!stack.empty()) {
                String s2 = stack.pop();
                add = s2.equals("+");
            }
            pre = add ? Math.addExact(pre, Integer.parseInt(s)) : Math.subtractExact(pre, Integer.parseInt(s));

        }
        return pre;

    }
}
